package org.brisling.medical.queryService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.StringUtil;
import org.brisling.medical.domain.MedicalInpatient;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>
 * Title: QueryInpatientService
 * </p>
 * <p>
 * Description: 住院信息查询service
 * </p>
 * <p>
 * Company: 长沙东勤信息科技发展有限公司
 * </p>
 * 
 * @author shura
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:05:46
 */
@RestController
@RequestMapping("/medicalInpatient/query")
public class QueryInpatientService extends AbstractBaseQueryService<MedicalInpatient> {

	@Autowired
	private ShiroSecurityService shiroSecurityService;
	@Autowired
	private QueryDictionaryService dicService;

	public QueryInpatientService() {
		this.moduleName = ConstSysParam.MODULE_INPATIENT;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = ConstSysParam.VIEW_PREFIX + this.getTableName(MedicalInpatient.class);
		this.clazz = MedicalInpatient.class;

		typeMap = this.getTypeMap(clazz);

		orderMap.put("outhospitalat", "desc");

	}

	@PersistenceContext(unitName = ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage() {
		return this.getBizMainPage();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage() {
		return this.getBizEditPage();
	}

	@RequestMapping("/bizInfoPage.action")
	public ModelAndView getBizInfoPage() {
		return new ModelAndView("/medical/medical_inpatient/popMain");
	}

	@RequestMapping("/getListDomain.action")
	public ListDomain<MedicalInpatient> getListDomain(@RequestBody(required = false) String body) {

		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap, true);

	}

	/**
	 * 获取业务数据统计值
	 * 
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getBizCount.action")
	public Long getBizCount(@RequestBody(required = false) String body) {
		Map<String, Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String, String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		return this.getBizCnt(paramMap, userid);
	}

	public Long getBizCnt(Map<String, String> paramMap, String userid) {
		if (!this.isSuperDept(userid, ConstSysParam.QUERY_ALL, "query_medical_all")) {
			String deptids = getUserDeptids(userid);
			paramMap.put("doct_depart_code_in", deptids);
		}
		return super.getBizCount(paramMap, null, null, null);
	}

	/**
	 * 获取业务数据统计值
	 * 
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getBizListDomain.action")
	public ListDomain<MedicalInpatient> getBizListDomain(@RequestBody(required = false) String body) {
		String sql = dicService.getSqlByBizcode("medical_inpatient_bizlist");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String, Object> map = this.getBodyParam(body);
		Map<String, String> conditionMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);

		String condition1 = "";
		String condition2 = "";
		if (conditionMap != null) {

			if (conditionMap.containsKey("outhospitalat_start") && conditionMap.containsKey("outhospitalat_end")) {
				condition1 = String.format(SysConfig.getConfig("dateGeTemplate"), "outhospitalat",
						conditionMap.get("outhospitalat_start"));

				condition1 = " where " + condition1 + " and " + String.format(SysConfig.getConfig("dateLeTemplate"),
						"outhospitalat", conditionMap.get("outhospitalat_end"));
			}

			if (conditionMap.containsKey("inquiry_item_code")) {
				condition2 = " where " + String.format(SysConfig.getConfig("strTemplate"), "inquiry_item_code",
						conditionMap.get("inquiry_item_code"));
			}
		}

		sql = String.format(sql, condition1, condition2, "%1$s");

		map.put(ConstSysParam.CONDITION_MAP_KEY, new HashMap<String, String>());
		if (!this.isSuperDept(userid, ConstSysParam.QUERY_ALL, "query_medical_all")) {
			map = this.addDeptConditionToMap(userid, map, "doct_depart_code");
		}
		return super.getListDomainByConditionAndOrder(sql, map, typeMap, orderMap, true);
	}

	@RequestMapping("/getList.action")
	public List<MedicalInpatient> getList(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "deptid", required = false) Integer deptid,
			@RequestParam(value = "sort", required = false) String sort) {

		StringBuilder sb = new StringBuilder();
		String sql = "";
		if (deptid != null) {
			String whereCorse = String.format(sb.append("\"deptid\" = %1$d").toString(), deptid);
			sql = String.format(this.TW_SQL, this.tableName, whereCorse);
		} else {
			sql = String.format(this.T_SQL, this.tableName);
		}

		return super.getPagedList(page, rows, sql);
	}

	/**
	 * 根据用户id查找用户信息
	 * 
	 * @param id
	 *            用户id
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOne.action")
	public MedicalInpatient getOne(@RequestParam(value = "id", required = false) Long id) {
		return super.getOne(id);
	}

	/**
	 * 根据用户唯一编码查找用户信息
	 * 
	 * @param identify
	 *            用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public MedicalInpatient getOneByIdentify(@RequestParam(value = "identify", required = false) String identify) {
		return super.getOneByIdentify(identify);
	}

	@RequestMapping("/getOneByField.action")
	public MedicalInpatient getOneByField(@RequestParam(value = "field", required = false) String field,
			@RequestParam(value = "fieldVal", required = false) String fieldVal) {
		return this.getOneByIdentify(field, fieldVal);
	}

	protected MedicalInpatient getOneByIdentify(String identify, String value) {

		String _identify = "identify";

		_identify = identify == null ? _identify : identify;
		StringBuilder sb = new StringBuilder();
		String sql = null;

		if (identify != null) {
			String whereCorse = String.format(sb.append("%1$s = \'%2$s\'").toString(), _identify, value);
			sql = String.format(
					"select * from (select I.DOCT_DEPART_CODE, I.DOCT_DEPART_NAME, I.DOCT_CODE,I.INHZOSPITALAT, I.INPATIENT_NO, I.INPATIENT_TYPE, I.IS_COMMENT, I.IS_DEATH, I.OUTHOSPITALAT, I.PATIENT_BIRTH, I.PATIENT_ID, I.PATIENT_NAME, I.PATIENT_NO, I.PATIENT_SEX, I.ZYHM, U.NAME doct_name from v_medical_inpatient i left join v_sysman_user u on i.doct_code = u.doct_code) WHERE %2$s",
					this.tableName, whereCorse);
			Query query = entityManager.createNativeQuery(sql);

			return (MedicalInpatient) super.reflectObjectMap(clazz, getSingalQueryResult(query), null);
		}
		return null;

	}

	public ListDomain<MedicalInpatient> getMyListDomain(String sql) {
		return super.getSqlListDomain(sql);
	}

	/**
	 * 按照患者编码查询患者住院记录，
	 * 
	 * @param patient_no
	 *            患者编码
	 * @return
	 */
	public List<MedicalInpatient> getListByPatientNo(String patient_no) {

		if (patient_no != null) {
			String sql = "select * from %1$s where patient_no = '%2$s' order by inhzospitalat desc";
			sql = String.format(sql, this.tableName, patient_no);
			return super.getAllList(sql);
		} else {
			return null;
		}
	}

	/**
	 * 查询当前在院患者
	 * 
	 * @param body
	 *            查询条件
	 * @return
	 */
	@RequestMapping("/getCurrentPatient.action")
	public List<MedicalInpatient> getCurrentPatient(Map<String, Object> map, String queryModule) {

		String _module = queryModule == null ? ConstSysParam.QUERY_MEDICAL_ALL : queryModule;
		String userid = "";
		if (map != null && map.containsKey("userid")) {
			System.out.println("userid: " + map.get("userid"));
			userid = map.get("userid").toString();
		}

		if (!this.isSuperDept(userid, ConstSysParam.QUERY_ALL, _module)) {
			String deptids = this.getJobDeptids(userid);
			String _filedName = "doct_depart_code";

			if (map == null) {
				map = new HashMap<String, Object>();
			}

			map.put(_filedName, deptids);
		}

		String sql = dicService.getSqlByBizcode("qry_current_patient");

		sql = StringUtil.formatSql(sql, map);

		return super.getAllList(sql);
	}
}
